const myUtils = require("../../utils/myUtils");
let db;
let ui;
Page({
  data: {
    questions: [],
    answer: [], //用户回答的内容
    dbData: {}, //提交到数据库的数据
    selectedAddress:null,
    checked:null,
    // checked:"checked"
    initComplete:false,
  },
  onShow: async function () {
    this.setData({
      initComplete:false
    });
    db = wx.cloud.database();
    ui = wx.getStorageSync("userInfo");
    await this.getQuestionsAndAnswers();
    this.setData({
      initComplete:true
    });
  },
  translateRadio(){

  },
  handleSubmit: async function () {
    if (!this.checkComplete()) {
      wx.showModal({
        title: '提示',
        content: '请填写所有问题!',
        showCancel: false,
        confirmText: '知道了',
      }).then(res => {
        if (res.confirm) {
          console.log('用户点击知道了');
        }
      });
    } else {

      const ui = wx.getStorageSync("userInfo");
      // const ui={
      //   openId:500
      // }
      const time = await myUtils.getTime();
      const _ = db.command;
      let name;
      let sex;
      let grade;
      let _class;
      let studentId;
      let major;
      //拼接数据准备上传
      /**
       * 数据库结构：
       * {
       *  data:[
       *    answer:[],
       *    openId:[],
       *    time:"",
       *    name:"",
       *    sex:"",
       *    grade:"",
       *    classes:"",
       *    studentId:"",
       *    major:""
       *  ]
       * }
       */
      
      for(let ans of this.data.answer){
        if(ans.questionName==="您的姓名是？"){
          name=ans.value;
        }
        else if(ans.questionName==="您的学号是？"){
          studentId=ans.value;
        }
        else if(ans.questionName==="您的专业是？"){
          major=ans.value;
        }
        else if(ans.questionName==="您的年级是？"){
          grade=ans.value;
        }
        else if(ans.questionName==="您的班级是？"){
          _class=ans.value;
        }
        else if(ans.questionName==="您的性别是？"){
          sex=ans.value;
        }
      }
      this.setData({
        dbData: {
          // openId: 500,
          openId: ui.openid,

          answer: this.data.answer,
          time: time,
          name:name,
          sex:sex,
          grade:grade,
          class:_class,
          studentId:studentId,
          major:major
        }
      });
      console.log("dbData",this.data.dbData);
      db.collection('user_info')
        .get().then(res => {
          console.log(res);
          console.log(res.data.length);
          if (res.data.length == 0) {
            db.collection('user_info')
              .add({
                data: {
                  data: [this.data.dbData]
                }
              }).then(res => {
                console.log("创建了userInfo表");
              })
          } else {//有表
            let flag = false;
            let dataIndex;
            let infos=res.data[0].data;
            let _id=res.data[0]._id;
            console.log("infos",infos);
            for (let index in infos) {
              if (infos[index].openId === ui.openid) {
                flag = true;
                dataIndex = index;
                break;
              }
            }
            console.log("flag:",flag);
            if (flag) { //如果有相同的openId，则覆盖
              db.collection('user_info')
                .doc(_id)
                .update({
                  data: {
                    [`data.${dataIndex}`]: this.data.dbData
                  }
                }).then(res => {
                  console.log("更新成功");
                })
            } else { //如果没有相同的openId，则插入
              db.collection('user_info')
                .doc(_id)
                .update({
                  data: {
                    data: _.push(this.data.dbData)
                  }
                }).then(res => {
                  console.log("插入成功");
                })
            }
          }
        });

      this.submitSuccess();
    }
  },
  submitSuccess(){
    wx.showModal({
      title: '提交成功',
      content: '您的问卷已提交成功!',
      showCancel: false,
      confirmText: '知道了',
    }).then(res => {
      if (res.confirm) {
        console.log('用户点击知道了');
      }
    });
  },
  initAnswer() {
    let answer = [];
    for (let quest of this.data.questions) {
      answer.push({
        questionId: quest._id,
        questionName:quest.question,
        type:quest.type,
        value: null
      });
    }
    this.setData({
      answer: answer
    });
    // console.log(this.data.answer);
  },
  getQuestionsAndAnswers:async function () {
    let res=await wx.cloud.callFunction({
      name: "get_question",
      data: {
        questionName: "question_user_info",
      },
    })
    this.setData({
      questions: res.result.data
    });
    this.initAnswer();
    res=await wx.cloud.callFunction({
      name:"get_user_info",
      data:{
        openId:ui.openid
      }
    });
    console.log(res);
    
    let answer=this.data.answer;
    console.log(answer);
    let historyAns=res.result.answer;

    for(let ans of answer){
      for(let hisAns of historyAns){
        if(ans.questionName===hisAns.questionName){
          ans.value=hisAns.value;
          break;
        }
      }
    }
    let checked=[];
    for(let ques of this.data.questions){
      let row=[];
      console.log(ques);
      if(ques.type!=="radio"){
        checked.push(null);
        continue;
      }
      for(let ans of answer){

        if(ques.question===ans.questionName){
          
          for(let index in ques.options){
            if(ques.options[index]===ans.value){
              row.push("checked");
            }
            else{
              row.push("");
            }
          }
          
          break;
        }
      }
      checked.push(row);
    }
    console.log(checked);
    this.setData({
      checked:checked
    })
    console.log(answer);
    this.setData({
      answer:answer
    });
    // console.log(this.data.questions);
  },
  onSliderChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const sliderValue = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = sliderValue;
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onInputChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const value = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = value;
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onRadioChange(e) {
    console.log(e);
    console.log(e.detail.value);
    const question_id = e.currentTarget.dataset.question_id;
    const value = e.detail.value;
    const options=e.currentTarget.dataset.question_options;
    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        // item.value = value;
        item.value=options[value];
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onAddressChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    
    const value = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = value;
        this.setData({
          selectedAddress:value
        });
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },

  checkComplete() {
    for (let item of this.data.answer) {
      if (item.value == null) {
        return false;
      }
    }
    return true;
  }

})